using System.ComponentModel;
using System.Text.Json;
using System.Text.Json.Serialization;
using Vin.Tool.Core.BasicTypeCategory;
using Vin.Tool.Core.ConvertCategory;
using Vin.Tool.Core.EnumCategory;

namespace Vin.Tool.Core.JsonCategory.Converters;

public class EnumToStringConverter<T> : JsonConverter<T?> where T : struct, Enum
{
    public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        if (reader.TokenType == JsonTokenType.Null || reader.TokenType == JsonTokenType.None)
            return default;

        if (reader.TokenType == JsonTokenType.String)
        {
            var enumText = reader.GetString();
            if (string.IsNullOrEmpty(enumText))
                return default;

            var enumType = Nullable.GetUnderlyingType(typeToConvert) ?? typeToConvert;
            return (T?)Enum.Parse(enumType, enumText, true);
        }

        if (reader.TokenType == JsonTokenType.Number)
        {
            var enumValue = reader.GetInt32();
            var enumType = Nullable.GetUnderlyingType(typeToConvert) ?? typeToConvert;
            return (T?)Enum.ToObject(enumType, enumValue);
        }

        return default;
    }

    public override void Write(Utf8JsonWriter writer, T? value, JsonSerializerOptions options)
    {
        if (value is not null && value is Enum @enum)
        {
            var enumType = value.GetType();
            var enumAttribute = @enum.GetCustomEnumAttribute<DescriptionAttribute>();
            // 获取字段的名字
            // var member = @enum.GetCustomAttribute<EnumMemberAttribute>();
            writer.WriteNumberValue(value.Value.ToInt());
            writer.WriteString(enumAttribute?.Description.ToCamelCase() ?? enumType.Name.ToCamelCase() ?? "",
                @enum.GetEnumMemberValue());
        }
        else
        {
            writer.WriteStringValue(value?.ToString() ?? "");
        }
    }
}